echo "Entering src/ directory"
cd src

bin="../bin"
obj="../obj"

CFLAGS="-c -fno-defer-pop -fstrength-reduce -finline-functions -fomit-frame-pointer -nostdlib -nostdinc -fno-builtin  -I. -I../include -L."

#gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o kb.o kb.c


# Bootloader
echo "Compiling bootloader..."
nasm -f bin -o boot.bin boot.asm

if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling bootloader"
	exit -1
fi

# Kernel stuff - This will generate kernel.bin
echo "Compiling kernel..."

gcc $CFLAGS  -o idt.o idt.c
if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling idt.c"
	exit -1
fi

nasm -f aout -o idt_asm.o idt.asm
if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling idt.asm"
	exit -1
fi


gcc $CFLAGS  -o io.o  io.c 
if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling io.c"
	exit -1
fi

gcc $CFLAGS -o screen.o  screen.c 
if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling screen.c"
	exit -1
fi

gcc $CFLAGS -o functions.o  functions.c 
if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling functions.c"
	exit -1
fi

nasm -f aout -o kernel.o  kernel.asm 
if [[ ! $? -eq 0 ]] ; then
	echo "Error compiling kernel.asm"
	exit -1
fi

ld -T link.ld kernel.o idt.o idt_asm.o io.o screen.o functions.o -o kernel.bin
if [[ ! $? -eq 0 ]] ; then
	echo "Error linking"
	exit -1
fi


mv *.o $obj
mv *.bin $bin

echo "Doing link on $obj"
cd $obj
ld kernel.o io.o idt.o idt_asm.o screen.o functions.o -o output.o

echo "Finished compiling"

cd ..

echo "Entering bin/ directory"
cd bin/

mv boot.img boot.img.bkp
qemu-img create boot.img 1M

if [[ ! -f boot.bin ]]; then
	echo "File boot.bin does not exist. Aborting..."
	exit -1
fi

dd if=boot.bin of=boot.img conv=nocreat,notrunc

if [[ ! -f kernel.bin ]]; then
	echo "File kernel.bin does not exist. Aborting..."
	exit -1
fi

dd if=kernel.bin of=boot.img bs=512 seek=1 conv=nocreat,notrunc

echo "Finished generating boot.img"
